{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3f42a094",
   "metadata": {},
   "source": [
    "### Python 中 `str.translate` 用法研究"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "490ff623",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function maketrans:\n",
      "\n",
      "maketrans(...)\n",
      "    Return a translation table usable for str.translate().\n",
      "    \n",
      "    If there is only one argument, it must be a dictionary mapping Unicode\n",
      "    ordinals (integers) or characters to Unicode ordinals, strings or None.\n",
      "    Character keys will be then converted to ordinals.\n",
      "    If there are two arguments, they must be strings of equal length, and\n",
      "    in the resulting dictionary, each character in x will be mapped to the\n",
      "    character at the same position in y. If there is a third argument, it\n",
      "    must be a string, whose characters will be mapped to None in the result.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(str.maketrans)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7237c5df",
   "metadata": {},
   "source": [
    "* 使用 `str.maketrans` 方法作为 `str.translate` 传入参数。`str.maketrans` 方法可传入表示映射关系的字典，形式非常灵活"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7efb51a8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s     ==> |python|abc|\n",
      "trans --> {97: 'x', 98: 'y', 99: 'z'} | after ==> |python|xyz| {97: 'x', 98: 'y', 99: 'z'}\n",
      "trans --> {'a': 'x', 'b': 'y', 'c': 'z'} | after ==> |python|xyz| {97: 'x', 98: 'y', 99: 'z'}\n",
      "trans --> {'a': 120, 'b': 121, 'c': 122} | after ==> |python|xyz| {97: 120, 98: 121, 99: 122}\n",
      "trans --> {97: 120, 98: 121, 99: 122} | after ==> |python|xyz| {97: 120, 98: 121, 99: 122}\n",
      "trans --> abc, xyz | after ==> |python|xyz| {97: 120, 98: 121, 99: 122}\n",
      "trans --> abc, xyz, pyt | after ==> |hon|xyz| {97: 120, 98: 121, 99: 122, 112: None, 121: None, 116: None}\n"
     ]
    }
   ],
   "source": [
    "maketrans_args = (\n",
    "    (dict(zip(map(ord, 'abc'), 'xyz')), ),            # 单参数 -- 序号 => 字符\n",
    "    (dict(zip('abc', 'xyz')), ),                      # 单参数 -- 字符 => 字符\n",
    "    (dict(zip('abc', map(ord, 'xyz'))), ),            # 单参数 -- 字符 => 序号\n",
    "    (dict(zip(map(ord, 'abc'), map(ord, 'xyz'))), ),  # 单参数 -- 序号 => 序号\n",
    "    ('abc', 'xyz'),                                   # 双参数\n",
    "    ('abc', 'xyz', 'pyt'),                            # 三参数 -- 最后一个参数表示这些字符映射成 None\n",
    ")\n",
    "\n",
    "s = '|python|abc|'\n",
    "print('s     ==>', s)\n",
    "for trans in maketrans_args:\n",
    "    trans_table = s.maketrans(*trans)\n",
    "    print('trans -->', ', '.join(map(str, trans)), '|',\n",
    "          'after ==>', s.translate(trans_table), trans_table)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d1062de",
   "metadata": {},
   "source": [
    "* 实现了 `__getitem__` 方法的对象：注意 `__getitem__` 传进来参数的类型为 `int`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "bb34904a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "|python|abc| ==> ipobcd\n"
     ]
    }
   ],
   "source": [
    "class Translator:\n",
    "    def __init__(self, trans, drop=None):\n",
    "        self.trans = trans\n",
    "        self.drop = set(map(ord, drop)) if drop else []\n",
    "\n",
    "    def __getitem__(self, k):\n",
    "        if k in self.drop:\n",
    "            return None\n",
    "        else:\n",
    "            return k + 1\n",
    "            # return chr(k + 1)\n",
    "\n",
    "    def __call__(self, s):\n",
    "        return s.translate(self)\n",
    "\n",
    "\n",
    "print('|python|abc|', '==>', '|python|abc|'.translate(Translator('abc', 'pyt|')))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
